<template>
  <div class="edit-container">
    <!-- 导航条 -->
  <van-nav-bar 
left-arrow 
@click-left="$router.go(-1)"
title="编辑资料"
></van-nav-bar>
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image fit="cover" round :src="userInfo.photo" />
    </div>
    <!-- 信息展示 -->
    <van-cell-group>
      <van-cell is-link title="名称" :value="userInfo.name" @click="editName"/>
      <van-cell is-link title="性别" :value="userInfo.gender?'女':'男'" 
      @click="showPopup=true"
      />
      <van-cell is-link title="生日" :value="userInfo.brithday" />
    </van-cell-group>
    <!-- 修改昵称的对话框 -->
<van-dialog
  v-model="showDialog"
  title="修改昵称"
  show-cancel-button
   @confirm="updateNickname"
>
  <van-field
    ref="input"
    placeholder="请输入昵称"
    v-model="newName"
  ></van-field>
</van-dialog>
<!-- 修改性别 -->
<van-popup v-model="showPopup" position="bottom">
  <van-nav-bar
    title="修改性别"
    left-text="取消"
    left-arrow
    @click-left="showPopup = false"
  >
  </van-nav-bar>
  <van-cell is-link title="男" @click="updateGender(0)" />
  <van-cell is-link title="女" @click="updateGender(1)" />
</van-popup>
  </div>
</template>

<script>
import {mapState} from "vuex"
import {editUserInfo} from "./user"

export default {
  name: 'edit',
  data(){
    return{
      showDialog:false,
      newName:'',
      showPopup:false
    }
  },
  computed:{
    ...mapState(['userInfo'])
  },methods:{
    editName(){
      this.showDialog=true
      this.newName=this.userInfo.name
      // setTimeout(()=>{this.$refs.input.focus()},1000)
      this.$nextTick(()=>{this.$refs.input.focus()},1000)
    },
    updateNickname(){
      editUserInfo({name:this.newName}).then(res=>{
        console.log(res)
        this.$store.commit('setUserInfo',{
         ...this.userInfo,  
          name:this.newName})
      })
    },
    updateGender (gender) {
  editUserInfo({ gender }).then(res => {
    //(1)弹窗提示
    this.$toast.success('更新成功!')
    //(2)更新vuex数据
    this.$store.commit('setUserInfo', {
      ...this.userInfo, //先传入原始数据
      gender
    })
    //(3)关闭弹窗 popup弹窗默认是点击空白区域关闭。我们点击的是cell需要手动关闭
    this.showPopup = false
  })
}
  }
}
</script>

<style lang="less">
.edit-container {
  // 导航条部分
  .van-nav-bar {
    background-color: #3196fa;
    .van-nav-bar__title {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
  }
  // 头像部分
  .avatar {
    padding: 20px 0;
    text-align: center;
    .van-image {
      width: 120px;
      height: 120px;
    }
  }
}
</style>
